package bbs;

import javax.servlet.http.HttpServletRequest;
import core.*;

public class BoardService {

    Board board;
    BoardAccessRule rule;
    User user;
    boolean admin;

    public BoardService(HttpServletRequest request, int boardId) throws Exception {
        board = BoardDAO.selectById(boardId);
        user = UserService.getCurrentUser(request.getSession());
        if (user != null) {
            rule = BoardAccessRuleDAO.selectByUserId(boardId, user.getId());
            admin = UserService.isCurrentUserInGroup(request.getSession(), "관리자");
        }
    }

    public int getCurrentUserId() {
        if (user == null) return 0;
        return user.getId();
    }

    public Board getBoard() {
        return board;
    }

    public boolean canListArticles() {
        if (admin) return true;
        if (user == null) return board.isGuestReadAllowed();
        return rule.canListArticles();
    }

    public boolean canCreateArticle() {
        if (admin) return true;
        if (user == null) return false;
        return rule.canCreateArticle();
    }

    public boolean canReadArticle(Article article) {
        if (admin) return true;
        if (user == null) return board.isGuestReadAllowed();
        if (rule.canReadArticle()) return true;
        return rule.canReadMyArticle() && article.getUserId() == user.getId();
    }

    public boolean canEditArticle(Article article) {
        if (admin) return true;
        if (user == null) return false;
        if (rule.canEditArticle()) return true;
        return rule.canEditMyArticle() && article.getUserId() == user.getId();
    }

    public boolean canDeleteArticle(Article article) {
        if (admin) return true;
        if (user == null) return false;
        if (rule.canDeleteArticle()) return true;
        return rule.canDeleteMyArticle() && article.getUserId() == user.getId();
    }

    public boolean canReadComment(Article article) {
        if (board.isCommentEnabled() == false) return false;
        return canReadArticle(article);
    }

    public boolean canCreateComment() {
        if (board.isCommentEnabled() == false) return false;
        if (admin) return true;
        if (user == null) return false;
        return rule.canCreateComment();
    }

    public boolean canEditComment(Comment comment) {
        if (board.isCommentEnabled() == false) return false;
        if (admin) return true;
        if (user == null) return false;
        return comment.getUserId() == user.getId();
    }

    public boolean canManageBoard() {
        if (admin) return true;
        if (user == null) return false;
        return rule.canManageBoard();
    }

}